const express = require('express');
const cors = require('cors');
const stockData = require('./stock_data');

const app = express();
const PORT = process.env.PORT || 5001;

// 中间件
app.use(cors());
app.use(express.json());

// 使用股票数据路由
app.use('/api/stocks', stockData);

// 模拟股票数据
const stockDataMock = {
  '000001': { name: '平安银行', market: 'A股', price: 15.23 },
  '000002': { name: '万科A', market: 'A股', price: 20.45 },
  '600519': { name: '贵州茅台', market: 'A股', price: 1800.00 },
  '002594': { name: '比亚迪', market: 'A股', price: 250.60 },
  '300750': { name: '宁德时代', market: 'A股', price: 420.80 },
  '00700': { name: '腾讯控股', market: '港股', price: 320.50 },
  '03690': { name: '美团', market: '港股', price: 180.20 },
  '09988': { name: '阿里巴巴', market: '港股', price: 85.30 },
  '02333': { name: '长城汽车', market: '港股', price: 12.80 },
  '01810': { name: '小米集团', market: '港股', price: 105.60 },
};

// 股票分析API - 模拟iFlow分析引擎
app.post('/api/analyze', async (req, res) => {
  try {
    const { stockCode } = req.body;
    
    // 验证股票代码
    if (!stockCode || !stockDataMock[stockCode]) {
      return res.status(400).json({
        error: 'Invalid stock code',
        message: '股票代码不存在'
      });
    }
    
    // 模拟iFlow分析过程
    const stockInfo = stockDataMock[stockCode];
    
    // 模拟iFlow分析结果
    const analysisResult = {
      stockCode: stockCode,
      stockName: stockInfo.name,
      market: stockInfo.market,
      currentPrice: stockInfo.price,
      conclusion: `根据iFlow分析，${stockInfo.name}(${stockCode})当前走势显示${Math.random() > 0.5 ? '上升' : '下降'}趋势，技术指标${Math.random() > 0.5 ? '强势' : '弱势'}，市场情绪${Math.random() > 0.5 ? '乐观' : '悲观'}。`,
      riskLevel: ['低', '中', '高'][Math.floor(Math.random() * 3)],
      targetPrice: (stockInfo.price * (1 + (Math.random() * 0.2 - 0.1))).toFixed(2),
      recommendation: ['买入', '持有', '卖出'][Math.floor(Math.random() * 3)],
      analysisTime: new Date().toISOString(),
      technicalIndicators: {
        RSI: Math.floor(Math.random() * 100),
        MACD: (Math.random() * 2 - 1).toFixed(2),
        KDJ: {
          K: Math.floor(Math.random() * 100),
          D: Math.floor(Math.random() * 100),
          J: Math.floor(Math.random() * 100)
        }
      }
    };
    
    // 模拟分析延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    res.json(analysisResult);
  } catch (error) {
    console.error('分析错误:', error);
    res.status(500).json({
      error: true,
      message: '服务器错误，请稍后重试'
    });
  }
});

// 获取股票列表API (保留用于向后兼容)
app.get('/api/stocks/list', (req, res) => {
  const stocks = Object.entries(stockDataMock).map(([code, info]) => ({
    value: code,
    label: `${code} - ${info.name}`
  }));
  res.json(stocks);
});

app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});
